import {  useContext, useState } from "react";
import { AppContext } from "../../Context/AppContext";
import { useNavigate } from "react-router-dom";


export default function Register() {
  const navigate = useNavigate()
  const { setToken} = useContext(AppContext)
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    password: "",
    password_confirmation: "",
  });
  const [errors, setErrors] = useState({});
  // 
  const handleSubmit = async (e) => {
    e.preventDefault();
    // console.log(formData);
    const res = await fetch("/api/register", {
      method: "POST",
      body: JSON.stringify(formData),
    });
 
    const data = await res.json();
    if (data.errors || !res.ok) {
      setErrors(data.errors);
    } else {
      localStorage.setItem("token", data.token)
         setToken(data.token)
      navigate('/')
      // navigate('/')
   
    }
  };

  return (
    <>
      <h1 className="title">注册</h1>
      <form onSubmit={handleSubmit} className="w-1/2 mx-auto space-y-6">
        <div>
          <input
            type="text"
            placeholder="用户名"
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
          />
          {errors.name && <p className="error">{errors.name}</p>}
        </div>
        <div>
          <input
            type="text"
            placeholder="邮箱"
            value={formData.email}
            onChange={(e) =>
              setFormData({ ...formData, email: e.target.value })
            }
          />
          {errors.email && <p className="error">{errors.email}</p>}
        </div>
        <div>
          <input
            type="password"
            placeholder="密码"
            value={formData.password}
            onChange={(e) =>
              setFormData({ ...formData, password: e.target.value })
            }
          />
          {errors.password && <p className="error">{errors.password}</p>}
        </div>
        <div>
          <input
            type="password"
            placeholder="确认密码"
            value={formData.password_confirmation}
            onChange={(e) =>
              setFormData({
                ...formData,
                password_confirmation: e.target.value,
              })
            }
          />
          {errors.password_confirmation && (
            <p className="error">{errors.password_confirmation}</p>
          )}
        </div>
        <button className="primary-btn">注册</button>
      </form>
    </>
  );
}
